﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ScrewTurn.Wiki.PluginFramework;
using ScrewTurn.Wiki;

using IdeaNMR.Shared;
using System.Text.RegularExpressions;

namespace IdeaNMR.Web.Core
{
    public class WikiPagesManager : IdeaNMRdbManager
    {
        /// <summary>
        /// Makes the database entry public and creates a wiki page.
        /// </summary>
        /// <param name="tID"></param>
        /// <param name="cT"></param>
        /// <returns>Returns the version number of newly published component.</returns>
        /// <exception cref="System.UnauthorizedAccessException">Thrown when user tries to publish somebodies else component.</exception>
        /// <exception cref="System.ArgumentExeption">Thrown when entry with id tID does is not found.</exception>
        public static int PublishComponent(Guid tID, ComponentType cT)
        {
            string name = null; // Will serve to create wiki page.
            int newVersionNumber = 0;

            name = setIsPrivate(tID, SessionFacade.CurrentUsername, out newVersionNumber, false);

            if (newVersionNumber == 0) WikiPagesManager.CreateWikiPage(cT, tID, name);
            return newVersionNumber;
        }

        /// <summary>
        /// Creates a new page for the component.
        /// </summary>
        /// <param name="cT">Type of component will be used in page name, Url and category.</param>
        /// <param name="cID">Id of component will be used in page Url</param>
        /// <param name="Name">Name of component will be used in page Name.</param>
        public static void CreateWikiPage(ComponentType cT, Guid cID, string Name)
        {
            string NewPageName;
            string NewPageTitle;

            List<string> Categories = new List<string>();
            string category = cT.ToWikiCategoryName();

            Categories.Add(category);
            NewPageTitle = category + " " + Name;
            NewPageName = string.Format("{0}_id_{1}", cT.ToString(), cID);

            addWikiPage(NewPageName, NewPageTitle, Categories);
        }

        private static bool addWikiPage(string NewPageName, string NewPageTitle, List<string> categories_names)
        {
            List<CategoryInfo> categories = new List<CategoryInfo>();

            PageInfo pg = Pages.FindPage(NewPageName);

            NamespaceInfo ni = Pages.FindNamespace("IdeaNMR");
            //Pages.Instance.CreateCategory("Experiment", (pg != null ? pg.Provider : null));
            bool bak = true;
            if (pg == null)
            {
                Pages.CreatePage(ni, NewPageName);
                pg = Pages.FindPage(NewPageName);
                bak = false;
                //txtUploadDirectory.Text = pg.Name;
            }
            else
            {
                Log.LogEntry("Page " + NewPageName + " already exists: new version created.", EntryType.Error, SessionFacade.CurrentUsername);
                return false;
            }
            Log.LogEntry("Page update requested for " + NewPageName, EntryType.General, SessionFacade.CurrentUsername);
            //Pages.ModifyPage(pg, NewPageTitle, SessionFacade.CurrentUsername, DateTime.Now, "", "", bak);
            Pages.ModifyPage(pg, NewPageTitle, SessionFacade.CurrentUsername, DateTime.Now, string.Empty, string.Empty, null, string.Empty, bak? SaveMode.Backup : SaveMode.Normal);

            foreach (string name in categories_names)
            {
                Pages.CreateCategory(ni, name);
                categories.Add(Pages.FindCategory(name));
            }
            Pages.Rebind(pg, categories.ToArray());

            return true;
        }

        public static string getCurrentPageName()
        {
            string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            return sRet;
        }

        public static void DeleteAllNMRPages()
        {
            //List<PageInfo> nmrPages = Pages. .AllPages.Where(pi => Regex.IsMatch(pi.Name, @"^(\w+)_id_([0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12})$")).ToList();
            //foreach (PageInfo pi in nmrPages)
            //{
            //    Pages.DeletePage(pi);
            //}
        }
    }

    public static partial class ComponentTypeExtensions
    {
        public static string ToWikiCategoryName(this ComponentType c)
        {
            string[] categories = { "Setup", "Pulse Program", "Wave Shape", "CPD Scheme", "Script" };
            return categories[(int)c];
        }
    }
}
